//
//  EntityManager.m
//  MapLink
//
//  Created by meng on 5/28/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "EntityManager.h"
#import <sqlite3.h>
#import "NotificationEntity.h"
#import "UserLocationEntity.h"
#import "GroupEntity.h"


static sqlite3 *database = nil;
static sqlite3_stmt *deleteStmt = nil;
static sqlite3_stmt *addStmt = nil;

@implementation EntityManager

+ (NSString *) getDocumentFolder {
	
	NSString *docpath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
	return docpath;
	
}


+ (void) copyDatabaseIfNeeded {
	
	
	//Using NSFileManager we can perform many file system operations.
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	NSString *dbPath = [EntityManager getDBPath];
	BOOL success = [fileManager fileExistsAtPath:dbPath]; 
	
	if(!success) {
		
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SQL.sqlite"];
		success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
		
		if (!success) 
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
	}	
}

+ (NSString *) getDBPath {
	
	//Search for standard documents using NSSearchPathForDirectoriesInDomains
	//First Param = Searching the documents directory
	//Second Param = Searching the Users directory and not the System
	//Expand any tildes and identify home directories.
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];	
	return [documentsDir stringByAppendingPathComponent:@"SQL.sqlite"];

}



+ (void) finalizeStatements {
	
	if(database) sqlite3_close(database);
	if(deleteStmt) sqlite3_finalize(deleteStmt);
	if(addStmt) sqlite3_finalize(addStmt);
}

+ (NSString*) getCurrentDateTimeSqlFormat {
	NSDateFormatter *format = [[NSDateFormatter alloc] init];
	[format setDateFormat:@"yyyy-MM-dd HH:mm"];
	
	NSDate *now = [[NSDate alloc] init];
	
	NSString *dateString = [format stringFromDate:now];
	[format release];
	[now release];
	return dateString;
	
}

+ (NSDecimalNumber *) convertFromFloat:(float) num {
	NSString *s = [NSString stringWithFormat:@"%f", num ];
	NSDecimalNumber *ds = [[[NSDecimalNumber alloc] initWithString:s] autorelease];
	return ds;
	
}


+ (NSString *) getDeviceUUID {
	NSString * uuid = [[UIDevice currentDevice] uniqueIdentifier] ;
	return uuid;
}

- (void) removeNotification:(NotificationEntity *)notificationObj {
	
	// sql statement
	NSString* sql = [NSString stringWithFormat:@"delete from Notification where id=%d", notificationObj.ID] ;
	NSString *dbPath = [EntityManager getDBPath];
	if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Error opening database");
		return;
		
	}
	
	char *err;
	if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
		NSAssert(0, @"Error deleting notification record from Notification table");
	}
	sqlite3_close(database);	

	
}

- (void) addNotification:(NotificationEntity *)notificationObj {
	
	NSString *nowDateString = [NSString stringWithString:[EntityManager getCurrentDateTimeSqlFormat]];
	
	NSString *sql = [NSString stringWithFormat:@"insert into Notification "
	            "(user_name, group_name, location_x, location_y, message, created_date, device_id, tstamp )" 
				" values ('%@', '%@', %f, %f, '%@', '%@', '%@', '%@')", 
				notificationObj.userName,	 
				notificationObj.groupName, 
				[notificationObj.locationX doubleValue],
				[notificationObj.locationY doubleValue], 
				[notificationObj.notificationMsg stringByReplacingOccurrencesOfString:@"'" withString:@"''"],
				notificationObj.createDate,
				notificationObj.deviceId,
				nowDateString ];
	
	NSString *dbPath = [NSString stringWithString:[EntityManager getDBPath]];

	if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Error opening database");
		return;
		
	}
	NSLog(@"insert notif sql > %@", sql);
	
	char *err;
	if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {

		NSAssert(0, @"Error inserting record in Notification Table");
		NSLog(@"%@", err);
	}

	sqlite3_close(database);
	
	
}



- (void) removeAllNotifications {
	// sql statement
	NSString* sql = [NSString stringWithString:@"delete from Notification"];
	NSString *dbPath = [NSString stringWithString:[EntityManager getDBPath]];
	if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Error opening database");
		return;
		
	}
	
	char *err;
	if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {

		NSAssert(0, @"Error deleting all records in Notification Table");
	}
	sqlite3_close(database);
	
	
}


- (NSMutableArray*) getNotificationList:(NSString *)group {
	
	NSString *sql = [NSString stringWithFormat:@"select "
					 "id,user_name,group_name,location_x,location_y,message,created_date,device_id "
					 "from Notification where group_name='%@' order by id desc",group];
	
	NSMutableArray *array = [[NSMutableArray alloc] init];
	NSString *dbPath = [EntityManager getDBPath];
	NSLog(@"%@", sql);
	
	if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		sqlite3_stmt *selectstmt;
		if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) {
			
			NSLog(@"SQLITE_OK");
			if (selectstmt) {
				while(sqlite3_step(selectstmt) == SQLITE_ROW) {
					NSLog(@"SQLITE_OK-while");

					NotificationEntity *nObj = [[NotificationEntity alloc] init];
					
					nObj.ID = sqlite3_column_int(selectstmt, 0); 
					nObj.userName =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
					nObj.groupName =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];			
					nObj.locationX =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 3)];
					nObj.locationY =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 4)];
					nObj.notificationMsg =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];	
					nObj.createDate =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 6)];				
					nObj.deviceId =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 7)];
					[array addObject:nObj];
					[nObj autorelease];

				}
			}
		}
	}
	else {
		sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.	
	}
	
	[array autorelease];
	
	return array;
	
	
}


- (void) removeUserLocation:(UserLocationEntity *) userLocationObject {
	// sql statement
	NSString* sql = [NSString stringWithFormat:@"delete from UserLocation where user_name='%@'", userLocationObject.userName] ;
	NSString *dbPath = [EntityManager getDBPath];
	if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Error opening database");
		return;
		
	}
	
	char *err;
	if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
		NSAssert(0, @"Error deleting user record from UserLocation table");
	}
	sqlite3_close(database);	
	
}


- (void) addUpdateUserLocation:(UserLocationEntity *) userLocationObject {
	UserLocationEntity *userLocationFromDb = [[self getUserLocation:userLocationObject.userName] retain];
	// check if exists
	
	NSString *curDateTime = [NSString stringWithString:[EntityManager getCurrentDateTimeSqlFormat]];
	
    // record does not exists, add new	
	if (!userLocationFromDb) {
		NSString *sql = [NSString stringWithFormat:@"insert into UserLocation " 
						  "( user_name, group_name,location_x, location_y, tstamp) "
						  "values ('%@', '%@', %f, %f, '%@')", 
						  userLocationObject.userName,
						  userLocationObject.groupName,
						  [userLocationObject.locationX doubleValue],
						  [userLocationObject.locationY doubleValue],
						  curDateTime ] ;
		
		NSString *dbPath = [NSString stringWithString:[EntityManager getDBPath]];
		if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
			sqlite3_close(database);
			NSAssert(0, @"Error opening database");
			[userLocationFromDb release];
			return;
			
		}
		
		char *err;
		if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
			sqlite3_close(database);
			NSAssert(0, @"Error inserting new UserLocation record into UserLocation Table");
		}
		sqlite3_close(database);	
		[userLocationFromDb release];
		
	}
	else {
		// not to change userLocationObject, just compare and change userLocationFromDB
		
		
		NSString *sql = [NSString stringWithFormat:@"update UserLocation set location_x=%f, location_y=%f, "
						  "tstamp='%@' where user_name='%@'",  
						  [userLocationObject.locationX doubleValue],
						  [userLocationObject.locationY doubleValue],
						  curDateTime, 
						  userLocationObject.userName];
		
		NSString *dbPath = [NSString stringWithString:[EntityManager getDBPath]];
		if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
			sqlite3_close(database);
			NSAssert(0, @"Error opening database");
			[userLocationFromDb release];
			return;
			
		}	
		
		
		char *err;
		if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
			NSAssert(0, @"Error updating UserLocation record into UserLocation Table");
		}

		[userLocationFromDb release];
		sqlite3_close(database);
		
	}	
	
	
}

- (void) removeAllUserLocations {
	// sql statement
	NSString* sql = [NSString stringWithString:@"delete from UserLocation"] ;
	NSString *dbPath = [EntityManager getDBPath] ;
	if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Error opening database");
		return;
		
	}
	
	char *err;
	if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Error deleting all records from UserLocation table");
	}
	sqlite3_close(database);
	
}

- (NSMutableArray *) getUserLocationsList {
	
	NSString *sql = [NSString stringWithString:@"select user_name, group_name,"
					 "location_x, location_y from UserLocation"];
	
	NSMutableArray *array = [[NSMutableArray alloc] init];

	NSString *dbPath = [NSString stringWithString:[EntityManager getDBPath]];
	
	if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		
		sqlite3_stmt *selectstmt;
		if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) {
			
						
			while(sqlite3_step(selectstmt) == SQLITE_ROW) {
				
				UserLocationEntity *nObj = [[UserLocationEntity alloc] init];

				nObj.userName =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
				nObj.groupName =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];			
				nObj.locationX =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 2)];
				nObj.locationY =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 3)];
				
				[array addObject:nObj];
				[nObj autorelease];
				
			}
		}
	}
	else {
		sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.	
	}
	

	[array autorelease];
	return array;	
	
	
}

- (UserLocationEntity *) getUserLocation: (NSString *) userName {
	
	NSString *sql = [NSString stringWithFormat:@"select user_name, group_name,"
					  "location_x, location_y from UserLocation where user_name = '%@'", userName] ;
	
	NSString *dbPath = [NSString stringWithString:[EntityManager getDBPath]];
	
	if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Error opening database");
		return nil;		
	}
	
		
	sqlite3_stmt *selectstmt;
	UserLocationEntity *nObj = nil;
	if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) {
	
			
		while(sqlite3_step(selectstmt) == SQLITE_ROW) {
				
			nObj = [[UserLocationEntity alloc] init];
				
			nObj.userName =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
			nObj.groupName =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];			
			nObj.locationX =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 2)];
			nObj.locationY =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 3)];
				
			[nObj autorelease];
			break;
				
		}
		
	}
	sqlite3_finalize(selectstmt);
	sqlite3_close(database);
	return nObj;
	
}

- (void) addUpdateGroup:(GroupEntity *) groupObject {
	GroupEntity* grpFromDB = [[self getGroup:groupObject.groupName] retain];
	
	// check if exists
	
	NSString *curDateTime = [NSString stringWithString:[EntityManager getCurrentDateTimeSqlFormat]];
 
    // record does not exists, add new	
	if (!grpFromDB) {
		NSString *sql = [NSString stringWithFormat:@"insert into Groups ( group_name, group_code, mp_location_x, "
															"mp_location_y, ownership, tstamp) "
														    "values ('%@', '%@', %f, %f, %d, '%@')", 
															groupObject.groupName,
															groupObject.groupCode,
															[groupObject.meetingPointLocationX doubleValue],
															[groupObject.meetingPointLocationY doubleValue],
															groupObject.ownership,
															curDateTime ];
		
		NSString *dbPath = [NSString stringWithString:[EntityManager getDBPath]];
		if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
			sqlite3_close(database);
			NSAssert(0, @"Error opening database");
			[grpFromDB release];
			return;
			
		}
		
		NSLog(@"sql> %@", sql);
		char *err;
		if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
			NSAssert(0, @"Error inserting new Group record into Groups Table");
			NSLog(@"err %@", err);
		}
		sqlite3_close(database);
		[grpFromDB release];
		
	}
	else {
		BOOL change = NO;
		// not to change groupObject, just compare and change grpFromDB
		if (grpFromDB.meetingPointLocationX != groupObject.meetingPointLocationX) {
			grpFromDB.meetingPointLocationX = groupObject.meetingPointLocationX;
			change = YES;
		}
		
		if (grpFromDB.meetingPointLocationY != groupObject.meetingPointLocationY) {
			grpFromDB.meetingPointLocationY = groupObject.meetingPointLocationY;
			change = YES;
		}
		
		if (!change) {
			[grpFromDB release];
			return;   // exit, no nee to update
		}
		
		NSString *sql = [NSString stringWithFormat:@"update Groups set mp_location_x=%f, mp_location_y=%f, "
						 "tstamp='%@' where group_name='%@'",  
						 [grpFromDB.meetingPointLocationX doubleValue],
						 [grpFromDB.meetingPointLocationY doubleValue],
						 curDateTime, 
						 grpFromDB.groupName];

		
		NSString *dbPath = [NSString stringWithString:[EntityManager getDBPath]];
		if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
			sqlite3_close(database);
			NSAssert(0, @"Error opening database");
			[grpFromDB release];
			return;
			
		}	
		
		
		char *err;
		if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
			NSAssert(0, @"Error updating  Group record into Groups Table");
		}		
		
		[grpFromDB release];
		sqlite3_close(database);
		
	}


}

- (void) removeAllGroups {
	
	// sql statement
	NSString* sql = [NSString stringWithString:@"delete from Groups"] ;
	NSString *dbPath = [EntityManager getDBPath];
	if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Error opening Database");
		return;
		
	}
	
	char *err;
	if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
		NSAssert(0, @"Error deleting all records in Groups Table");
	}
	sqlite3_close(database);	
	
}

- (NSMutableArray*) getGroupsList {
	NSString *sql = [NSString stringWithString:@"select group_name, group_code,"
					 "mp_location_x, mp_location_y, ownership from Groups"];
	
	NSMutableArray *array = [[NSMutableArray alloc] init];
	
	NSString *dbPath = [EntityManager getDBPath];
	
	if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		
		sqlite3_stmt *selectstmt;
		if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) {
			
			
			
			while(sqlite3_step(selectstmt) == SQLITE_ROW) {
				
				GroupEntity *nObj = [[GroupEntity alloc] init];

				nObj.groupName =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
				nObj.groupCode =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];				
				nObj.meetingPointLocationX =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 2)];
				nObj.meetingPointLocationY =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 3)];
				nObj.ownership = sqlite3_column_int(selectstmt, 4);
				
				[array addObject:nObj];
				[nObj autorelease];
				
			}
			sqlite3_finalize(selectstmt);
		}
	}
	else {
		sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.	
	}
	
	[array autorelease];
	
	return array;		
}

- (GroupEntity *) getGroup: (NSString *) groupName {

	NSString *sql = [NSString stringWithFormat:@"select group_name, group_code,"
					  "mp_location_x, mp_location_y, ownership from Groups where group_name='%@'", groupName];	
	
	NSString *dbPath = [EntityManager getDBPath];
	
	if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Error opening database");
		return nil;		
	}	
	
	GroupEntity *nObj =nil;
	
	sqlite3_stmt *selectstmt;
	if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) {
	

		while(sqlite3_step(selectstmt) == SQLITE_ROW) {
			
			nObj = [[GroupEntity alloc] init];
			
			nObj.groupName =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
			nObj.groupCode =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];				
			nObj.meetingPointLocationX =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 2)];
			nObj.meetingPointLocationY =  [EntityManager convertFromFloat:(float)sqlite3_column_double(selectstmt, 3)];
			nObj.ownership = sqlite3_column_int(selectstmt, 4);

			[nObj autorelease];
			break;  // expect only 1 record
			
		}
		
		sqlite3_finalize(selectstmt);
	}	
	
	sqlite3_close(database);

	
	return nObj;
	
	
}


+ (int) getCount: (NSString*) sqlText {
    int count = 0;
	
	NSString *dbPath = [EntityManager getDBPath];
    if (sqlite3_open([dbPath  UTF8String], &database) == SQLITE_OK) 
    {
        const char* sqlStatement = [sqlText UTF8String];
        sqlite3_stmt* statement;
		
        if( sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK ) 
        {
            if( sqlite3_step(statement) == SQLITE_ROW )
                count  = sqlite3_column_int(statement, 0); 
        }
        else
        {
            NSLog( @"Failed from sqlite3_prepare_v2. Error is:  %s", sqlite3_errmsg(database) );
        }
		
        // Finalize and close database.
        sqlite3_finalize(statement);
        sqlite3_close(database);
    }
	
    return count;
}

+ (void) clearDatabase:(EntityManager *) entityMgr {
	[entityMgr removeAllGroups];
	[entityMgr removeAllUserLocations];
	[entityMgr removeAllNotifications];
	
}


+ (void) test:(EntityManager *) entityMgr  {
	
	// test GroupEntity
	
	NSLog(@"SQL.sqlite in: %@", [EntityManager getDBPath]);
	
	GroupEntity *grp = [[GroupEntity alloc] init];
	grp.groupName = @"group 1";
	grp.groupCode = @"grpcode12345";
	grp.meetingPointLocationX = [NSDecimalNumber decimalNumberWithString:@"111.111"];
	grp.meetingPointLocationY = [NSDecimalNumber decimalNumberWithString:@"555.555"];
	grp.ownership = 1;
	NSLog(@"insert new group: groupName=%@, groupCode=%@, meetingPointX=%f, meetingPointY=%f, ownership=%d", 
						grp.groupName, grp.groupCode, [grp.meetingPointLocationX doubleValue], [grp.meetingPointLocationY doubleValue],
						grp.ownership);
	[entityMgr addUpdateGroup:grp];
	
	// read back group
	GroupEntity * grpReadBack = [entityMgr getGroup:grp.groupName];
	[grpReadBack retain];
	NSLog(@"Read back group from DB: groupName=%@, groupCode=%@, meetingPointX=%f, meetingPointY=%f, ownership=%d", 
		  grpReadBack.groupName, grpReadBack.groupCode, [grpReadBack.meetingPointLocationX doubleValue], [grpReadBack.meetingPointLocationY doubleValue],
		  grpReadBack.ownership);
	[grpReadBack release];
	
				   
	// Change group meeting point info
	grp.meetingPointLocationX = [NSDecimalNumber decimalNumberWithString:@"222.222"];
	grp.meetingPointLocationY = [NSDecimalNumber decimalNumberWithString:@"777.777"];
	NSLog(@"Update Group Meeting Point in DB with meetingPointX=%f, meetingPointY=%f", 
		  [grp.meetingPointLocationX doubleValue], [grp.meetingPointLocationY doubleValue]);
	[entityMgr addUpdateGroup:grp];
	GroupEntity *grpReadBack2 = [entityMgr getGroup:grp.groupName];
	[grpReadBack2 retain];
	NSLog(@"Read back group from DB after meeting point change: groupName=%@, groupCode=%@, meetingPointX=%f, meetingPointY=%f, ownership=%d", 
		  grpReadBack2.groupName, grpReadBack2.groupCode, [grpReadBack2.meetingPointLocationX doubleValue], [grpReadBack2.meetingPointLocationY doubleValue],
		  grpReadBack2.ownership);	
	
	[grp release];
	[grpReadBack2 release];
	
	
	
	// Get the list of groups
	NSLog(@"Test getGroupsList method");
	NSMutableArray *array = [entityMgr getGroupsList];
	[array retain];
	for (GroupEntity *g in array) {
		NSLog(@"Iterate group from DB: groupName=%@, groupCode=%@, meetingPointX=%f, meetingPointY=%f, ownership=%d", 
			  g.groupName, g.groupCode, [g.meetingPointLocationX doubleValue], [g.meetingPointLocationY doubleValue],
			  g.ownership);
	}
	[array release];
	
	
	// Test Notification
	NotificationEntity *notif = [[NotificationEntity alloc] init];
	notif.userName = @"horri";
	notif.groupName= @"group 1";
	notif.deviceId = [EntityManager getDeviceUUID];
	notif.locationX = [NSDecimalNumber decimalNumberWithString:@"333.0"];
	notif.locationY = [NSDecimalNumber decimalNumberWithString:@"444.0"];
	notif.notificationMsg = @"Hello there";
	notif.createDate = [EntityManager getCurrentDateTimeSqlFormat];
				
	NSLog(@"insert new notification: userName=%@, groupName=%@,  "
		  "locationX=%f, locationY=%f, notificationMsg=%@, createDate=%@",
		  notif.userName, notif.groupName, [notif.locationX doubleValue], [notif.locationY doubleValue],
		  notif.notificationMsg, notif.createDate);
	NSLog(@"Test notification insert into DB");
	[entityMgr addNotification:notif];
	

	notif.userName = @"wise guy";
	notif.groupName= @"group 1";
	notif.deviceId = [EntityManager getDeviceUUID];
	notif.locationX = [NSDecimalNumber decimalNumberWithString:@"777.0"];
	notif.locationY = [NSDecimalNumber decimalNumberWithString:@"777.0"];
	notif.notificationMsg = @"Saw you message";
	notif.createDate = [EntityManager getCurrentDateTimeSqlFormat];	
	
	NSLog(@"insert 2nd new notification: userName=%@, groupName=%@, "
		  "locationX=%f, locationY=%f, notificationMsg=%@, createDate=%@",
		  notif.userName, notif.groupName,  [notif.locationX doubleValue], [notif.locationY doubleValue],
		  notif.notificationMsg, notif.createDate);
	NSLog(@"Insert 2nd new notification insert into DB");
	[entityMgr addNotification:notif];
	
	NSLog(@"Read back all notification");
	NSMutableArray *narray = [entityMgr getNotificationList:notif.groupName];
	[narray retain];
	for (NotificationEntity *n in narray) {
		NSLog(@"Iterate notification list from DB: id=%d, userName=%@, groupName=%@, "
			  "locationX=%f, locationY=%f, notificationMsg=%@, createDate=%@",
			  n.ID, n.userName, n.groupName, [n.locationX doubleValue], [n.locationY doubleValue],
			  n.notificationMsg, n.createDate);			
	}
	[narray release];
	[notif release];
	
	// Test notification count 
	int count = [EntityManager getCount:@"select count(*) from Notification"];
	NSLog(@"Number of notifcation %d", count);
	
	// Delete Notification
	NSLog(@"Deleting notification id=1 from DB");
	NotificationEntity *d = [[NotificationEntity alloc] init];
	d.ID =1;
	[entityMgr removeNotification:d];
	[d release];
	
    count = [EntityManager getCount:@"select count(*) from Notification"];
	NSLog(@"Count after notification id=1 deleted, Number of notification left %d", count);	
	

	
	
	NSLog(@"UserLocationEntity class not tested");
	NSLog(@"End of entity manager test completed");
	
	
	
	
	
}


@end




